<?php

namespace App\Services;
use App\Models\Crm_Slip;
use App\Models\Crm_Slip_Config;
use App\Models\Crm_Slip_Reply;
use App\Models\Crm_Slip_Template;
use App\Traits\External;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Throwable;

class SlipService
{
    public function updateSlipStatus($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Slip::find($params['id']);
            $res->status = $params['status'];

            if(!$res->save()){
                throw new \Exception("更新Crm_Slip纸条状态失败" );
            }
            DB::commit();

            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function getSlipBase($params)
    {
        return Crm_Slip_Config::getFilter($params)->first();
    }

    public function slipBaseUpdate($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Slip_Config::find($params['id']);
            $res->isopen = $params['isopen'];
            $res->isallow = $params['isallow'];
            $res->notvipnums = $params['notvipnums'];
            $res->vipnums = $params['vipnums'];
            $res->onreplynums = $params['onreplynums'];

            if(!$res->save()){
                throw new \Exception("更新Crm_Slip纸条状态失败" );
            }
            DB::commit();

            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function getSlipTemplate($params)
    {
        $result = Crm_Slip_Template::getFilter($params)->Nodel()->orderBy('order','desc')->get();
        foreach ($result as $key => $value){
            $result[$key]['reply'] = $value->hasManyReply()->get();
        }
        return $result;
    }

    public function slipTemplateSave($params)
    {
        try {
            $reply = json_decode($params['reply'],true);
            $tid = 0;
            // 开始数据库事务
            DB::beginTransaction();

            if(!empty($params['id'])) {
                $tid = $params['id'];
                $res = Crm_Slip_Template::find($params['id']);
                $res->content = $params['content'];
                if(!$res->save()){
                    throw new \Exception("更新Crm_Slip_Template纸条模板内容失败" );
                }
                Crm_Slip_Reply::where('agencyid',$params['aid'])->where('tid',$params['id'])->delete();

            }else{
                $maxValue = Crm_Slip_Template::max('order');
                $res = Crm_Slip_Template::create([
                    'agencyid' => $params['aid'],
                    'content' => $params['content'],
                    'order' => $maxValue + 1,
                ]);

                if(!$res->save()){
                    throw new \Exception("添加Crm_Slip_Template纸条模板内容失败" );
                }
                $tid = $res->id;
            }
            foreach ($reply as $item){
                Crm_Slip_Reply::create([
                    'agencyid' => $params['aid'],
                    'tid' => $tid,
                    'content' => $item['content']
                ]);
            }
            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function slipTemplateDel($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Slip_Template::find($params['id']);
            $res->is_del = 'Y';

            if(!$res->save()){
                throw new \Exception("更新Crm_Slip纸条状态失败" );
            }
            DB::commit();

            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function slipTemplateStatusUpdate($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Slip_Template::find($params['id']);
            $res->status = $params['status'];

            if(!$res->save()){
                throw new \Exception("更新Crm_Slip纸条状态失败" );
            }
            DB::commit();

            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function slipTemplateOrderUpdate($params)
    {
        $order = json_decode($params['orders'],true);
        $num = count($order);
        try {
            // 开始数据库事务
            DB::beginTransaction();
            for ($i = 1;$i <= $num; $i++){
                $res = Crm_Slip_Template::find($order[$i-1]['id']);
                $res->order = $num - ($i-1);
                if(!$res->save()){
                    throw new \Exception("更新Crm_Slip纸条排序失败" );
                }
            }
            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function getSlipList($params)
    {
        $result = Crm_Slip::getFilter($params)
            ->select(['id','mid','otherid','content','status','created_at','receive_at'])
            ->paginate($params['pageSize']);
        $list['total'] = $result->total();
        $result = External::optionResult($result,3);
        $list['list'] = $result;

        return $list;
    }
}
